<template>
  <div
    class="is-mobile"
    v-if="isMobile"
    :class="isWxAlipay ? '' : 'browser-box'"
  >
    <van-nav-bar :title="pageTitle" v-if="titleShow && !isWxAlipay" />
    <router-view v-slot="{ Component, route }">
      <keep-alive>
        <component
          v-if="route.meta.keepAlive"
          :is="Component"
          :key="route.path"
        />
      </keep-alive>
      <component
        v-if="!route.meta.keepAlive"
        :is="Component"
        :key="route.path"
      />
    </router-view>
    <!-- <van-tabbar v-model="active" @change="onChange" v-if="active == 0 || active == 1">
    <van-tabbar-item icon="home-o">首页</van-tabbar-item>
    <van-tabbar-item icon="contact">我的</van-tabbar-item>
  </van-tabbar> -->
    <van-popup v-model:show="showBottomVip" round closeable position="bottom">
      <van-nav-bar title="开通会员" />
      <div class="vip-main">
        <div class="vip-main-text">开通会员享受更多优惠</div>
        <div class="vip-list">
          <div class="vip-item" v-for="item in vipList" :key="item.id">
            <i>
              {{ item.name }}
            </i>
            <p>
              <span>
                {{ item.price }}
              </span>
            </p>
          </div>
        </div>
        <div class="footer-box">
          <van-button round type="primary">开通会员</van-button>
        </div>
      </div>
    </van-popup>
    <div class="page-loading" v-if="pageLoading">
      <div class="page-loading-main">
        <van-loading color="#0094ff">加载中...</van-loading>
      </div>
    </div>
  </div>
  <div class="not-mobile" v-else>
    <van-empty image="error" description="请在手机上预览" />
  </div>
</template>
<script setup>
import { ref, watch, computed, onMounted } from "vue";

import { useRoute, useRouter } from "vue-router";

import { showToast } from "vant";
import { appid, wwwUrl } from "@/utils/constant";

import userOrderStore from "@/store/index.js";

import {
  GetOpenid,
} from "@/api/mine/index.js";

import EventBus from "@/utils/EventBus";

let { setUserInfo, getIsPageLoading } = userOrderStore();
let isMobile = ref(false);
let route = useRoute();
let router = useRouter();

let userInfo = localStorage.getItem("userInfo");
if (userInfo) {
  setUserInfo(JSON.parse(userInfo));
}

const active = ref(0);
const titleShow = ref(false);

let pageTitle = ref("首页");

let pageLoading = computed(() => {
  return userOrderStore().getIsPageLoading;
});

watch(
  () => route,
  () => {
    console.log(route.meta.title);
    pageTitle.value = route.meta.title;
    active.value = route.meta.active;
    titleShow.value = route.meta.titleShow;
    document.title = route.meta.title;
  },
  {
    deep: true,
  }
);

const onChange = (ev) => {
  let name = ev == 0 ? "index" : "mine";
  router.push({
    name,
  });
  console.log(ev, "ev");
};

let showBottomVip = ref(false);
let vipList = ref([
  {
    id: 1,
    name: "普通会员",
    icon: "",
    price: 60.0,
  },
  {
    id: 2,
    name: "会员月卡",
    icon: "",
    price: 60.0,
  },
  {
    id: 3,
    name: "会员季卡",
    icon: "",
    price: 60.0,
  },
  {
    id: 4,
    name: "会员年卡",
    icon: "",
    price: 60.0,
  },
]);
const showCustomPage = () => {
  // let customData = JSON.stringify({
  //   action: "onIframeReady",
  //   displayStyle: "SHOW_CUSTOM_PAGE",
  //   height: 900,
  // });
  // parent.postMessage(customData, "https://payapp.weixin.qq.com");
};

const isMobileBrowser = () => {
  const mobileKeywords = [
    "Mobile",
    "Android",
    "iPhone",
    "iPad",
    "Windows Phone",
    "BlackBerry",
    "Symbian",
    "Opera Mobi",
    "Maemo",
    "Meego",
    "Nintendo DS",
    "Nintendo",
    "PSP",
    "Kindle",
    "PlayStation",
  ];
  const userAgent = navigator.userAgent;
  for (let i = 0; i < mobileKeywords.length; i++) {
    const keyword = mobileKeywords[i];
    const regex = new RegExp(keyword, "i");
    if (regex.test(userAgent)) {
      return true;
    }
  }
  return false;
};

isMobile.value = isMobileBrowser();

let isWxAlipay = ref(false);
let userAgent = navigator.userAgent;
var ua = window.navigator.userAgent.toLowerCase();

if (
  ua.match(/MicroMessenger/i) == "micromessenger" ||
  /AlipayClient/.test(window.navigator.userAgent)
) {
  isWxAlipay.value = true;
} else {
  isWxAlipay.value = false;
}

const is_weixn = () => {
  var ua = navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == "micromessenger") {
    return true;
  } else {
    return false;
  }
};

const getOpenidFn = async () => {
  //先判断有没有授权(判断地址栏code，有就-用户同意了授权，没有-没授权或者拒绝授权)
  // let str = route.query.code; //此处使用的是history路由模式，hash这么拿不到。
  let _params = queryURLParams(window.location.href);
  if (_params.code) {
    // 走后端接口(把code传给后台，让后台根据code获取openID与用户信息)
    let params = {
      code: _params.code,
    };
    // setIsPageLoading(true)
    let data = await GetOpenid(params);
    console.log(data, "a");
    if (data.openid) {
      localStorage.setItem("openid", data.openid);
      //拿到了ACCESS_TOKEN与用户openid，跳转到登录页面
      let jspParams = {
        url: window.location.href,
      };
      console.log(jspParams, "jspParams");
      try {
        let dataJsp = await getJspToken(jspParams);
        wx.config({
          debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: appid, // 必填，公众号的唯一标识
          timestamp: dataJsp.data.timestamp, // 必填，生成签名的时间戳
          nonceStr: dataJsp.data.nonceStr, // 必填，生成签名的随机串
          signature: dataJsp.data.signature, // 必填，签名
          jsApiList: ["checkJsApi", "chooseWXPay"], // 必填，需要使用的JS接口列表
        });
        wx.ready(function (res) {
          wx.checkJsApi({
            jsApiList: ["chooseWXPay"],
            success: (res) => {
              console.log("checked api:", res);
            },
            fail: (err) => {
              console.log("check api fail:", err);
            },
          });
          // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        });
        return;
      } catch (error) {}
    } else {
    }
  }
};
const queryURLParams = (URL) => {
  let url = URL.split("?")[1];
  const urlSearchParams = new URLSearchParams(url);
  const params = Object.fromEntries(urlSearchParams.entries());
  return params;
};

const getCode = () => {
  //没授权先授权,授权后会有一个code在地址栏上
  let params = queryURLParams(window.location.href);
  if (params.code) {
    let _code = localStorage.getItem("code");
    // console.log(_code != params.code, '996')
    if (_code != params.code) {
      localStorage.setItem("code", params.code);
      getOpenidFn();
    }
    return;
  }
  // return
  window.location.href =
    "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
    appid +
    "&redirect_uri=" +
    encodeURIComponent(window.location.href) +
    "&response_type=code&connect_redirect=1&scope=snsapi_base&state=state#wechat_redirect";
};

// 微信环境获取code
if (is_weixn()) {
  getCode();
}

onMounted(() => {
  showCustomPage();
});
// getCode();
</script>


<style lang="scss" scoped>
.vip-main {
  padding: 1em 0.5em 1em 0;
}

.vip-list {
  display: flex;

  .vip-item {
    position: relative;
    border: 0.18em solid #ccc;
    width: 25%;
    padding: 1em 0.5em 0 0.5em;
    border-radius: 0.4em;
    margin-left: 0.5em;
    overflow: hidden;

    i {
      position: absolute;
      top: 0;
      left: 0;
      border-radius: 0 0 0.5em 0;
      padding: 0.25em 0.5em;
      font-size: 0.5em;
      color: #333;
      background-color: #f2f2f2;
    }

    p {
      text-align: center;

      span {
        text-align: center;
        font-size: 1.8em;
        line-height: 2.5;
        font-weight: bold;
        color: #f00;
        margin-left: -0.25em;

        &::before {
          content: "￥";
          font-size: 0.5em;
        }
      }
    }
  }
}

.van-button {
  width: calc(100% - 0.5em);
  margin: 1em 0.5em 0 0.5em;
}

.vip-main-text {
  color: #333;
  padding: 0 0.5em;
  margin-bottom: 1em;
}

.page-loading {
  position: fixed;
  z-index: 999999999999;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;

  .page-loading-main {
    padding: 10px;
    background: #fff;
    border-radius: 8px;
  }
}
.not-mobile {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50vh;
}
.browser-box {
  :deep(.order-index-container) {
    height: calc(100vh - 88px);
  }
}
</style>
